<?php

namespace app\helps;
use app\facade\Redis;
use think\Db;

class OrderHelper{
        public function __construct(){
            $this->userHelper = new UserHelper();
            $this->sell = new CreateSell();
            $this->smsHelper = new SmsHelper();
        }

    /**
     * 订单创建了
     * @param $order
     */
    public function create($sell,$book) {
        $data =[];
        //1待支付 2 待确认 3 已完成 4 取消 5申述中
        $data["order_status"]=1;
        $data["s_id"]=$sell["id"];
        $data["create_time"]=date('Y-m-d H:i:s');
        $data["buy_id"]=$book["uid"];
        // buy name为紧急联系人
        $data["buy_name"]=$book["nick_name"];
        $data["buy_user_name"]=$book["username"];

        $id = Db::table("tb_mt_order")->insertGetId($data);
        if (!$id){
          return "订单入库失败";
        }
        //订单修改记录
        $record= "订单配成功";
        $mark = "预定人为".$book["uid"]."-".$book["username"];
        $resRecord = $this->create_order_record($id,$sell["sn"],$record,$mark);
        if (!$resRecord){
            return "订单记录入库失败";
        }
        //出售表 修改状态为匹配中
        $updateSell = [];
        $updateSell["status"]=2;
        $resSell =  Db::table("tb_mt_sell")->where("id",$sell["id"])->update($updateSell);
        if (!$resSell){
            return "出售表更新失败";
        }
        $resSms =$this->smsHelper->sendSmsByMacherOrderRecord($book["uid"],$book["username"],$sell["sn"]);
        if (!$resSms){
            return "发送短信记录失败";
        }

        Redis::hset("order_status_machered",$book["uid"],1);
        return 1;
    }

    /**
     * 强制匹配
     * @param $order
     */
    public function createMachterSys($sell,$sysUser) {
        $data =[];
        //1待支付 2 待确认 3 已完成 4 取消 5申述中
        $data["order_status"]=1;
        $data["s_id"]=$sell["id"];
        $data["create_time"]=date('Y-m-d H:i:s');
        $data["buy_id"]=$sysUser["uid"];
        //紧急联系人
        $data["buy_name"]=$sysUser["nick_name"];
        $data["buy_user_name"]=$sysUser["username"];
        $data["froce"]=1;//强制匹配
        $id = Db::table("tb_mt_order")->insertGetId($data);
        if (!$id){
            return "订单入库失败";
        }
        //订单修改记录
        $record= "订单配成功";
        $mark = "后台强制匹配".$sysUser["uid"]."-".$sysUser["username"];
        $resRecord = $this->create_order_record($id,$sell["sn"],$record,$mark);
        if (!$resRecord){
            return "订单记录入库失败";
        }
        //出售表 修改状态为匹配中
        $updateSell = [];
        $updateSell["status"]=2;
        $resSell =  Db::table("tb_mt_sell")->where("id",$sell["id"])->update($updateSell);
        if (!$resSell){
            return "出售表更新失败";
        }
        if ($sysUser["uid"]>0){
            $resSms =$this->smsHelper->sendSmsByMacherOrderRecord($sysUser["uid"],$sysUser["username"],$sell["sn"]);
            if (!$resSms){
                return "发送短信记录失败";
            }
            Redis::hset("order_status_machered",$sysUser["uid"],1);
        }
        return 1;
    }


    /**
     * 订单申诉了
     * @param $order
     */
    public function orderAppeal($view_order,$appealData) {
        $data =[];
        $data["uid"]=$view_order["sell_uid"];
        $data["user_name"]=$view_order["sell_user_name"];
        $data["content"]=$appealData["content"];
        $data["img"]=$appealData["img"];
        $data["oid"]=$appealData["id"];
        $data["type"]=$appealData["type"];
        $data["osn"]=$view_order["sell_sn"];
        $data["create_time"]=date('Y-m-d H:i:s');
        $appeal =  Db::table("tb_mt_appeal")->insertGetId($data);
        if (!$appeal){
            return "申诉表入库失败";
        }
        //订单修改状态 为申述中
        $updateOrderData = [];
        $updateOrderData["order_status"]=5;
        $resOrder =  Db::table("tb_mt_order")->where("id",$view_order["id"])->update($updateOrderData);
        if (!$resOrder){
            return "订单表入库失败";
        }
        //订单修改记录
        $record= "用户提交订单申诉";
        $mark = "申诉人:".$view_order["sell_uid"]."-".$view_order["sell_user_name"].":申诉标识:";
        $orderRecordResult = $this->create_order_record($view_order["id"],$view_order["sell_sn"],$record,$mark);
        if (!$orderRecordResult){
            return "订单记录表入库失败";
        }
        return 1;
    }

    /**
     * 订单申诉成功（卖家申诉）
     * @param $order
     * @param $appeal
     */
    public function orderAppealSellOk($view_order,$appeal) {
         // 1 ---- 改变申诉表 申诉状态
        //0 申述中 1 卖家申述成功 2 卖家申述失败
        $appealData["appeal_result"]=1;
        $appealData["finish_time"]=date('Y-m-d H:i:s');
        $appealResult =  Db::table("tb_mt_appeal")->where("id",$appeal["id"])->update($appealData);
        if (!$appealResult){
            return "申诉表改变状态失败";
        }
        // 2 ---- 修改订单状态
        //1待支付 2 待确认 3 已完成 4 取消 5申诉中 6申诉成功，7判定
        $data =[];
        $data["order_status"]=6;
        $data["cancle_time"]=date('Y-m-d H:i:s');
        $data["finish_time"]=date('Y-m-d H:i:s');
        $resOrder =  Db::table("tb_mt_order")->where("id",$view_order["id"])->update($data);
        if (!$resOrder){
            return "订单修改失败";
        }
        // 3 ---- 修改订单出售表状态
        //1 收益中 2 匹配中 3 用户取消再次待卖 4 申述成功再次待卖 5销毁 6判定代卖 7 完成
        $updateSell = [];
        $updateSell["status"]=4;
        $resSell =  Db::table("tb_mt_sell")->where("id",$view_order["sell_id"])->update($updateSell);
        if (!$resSell){
            return "出售表更新失败";
        }

        //4 ---- 订单修改记录
        $record= "卖家申诉成功,订单恢复到质押中";
        $mark = "卖家".$view_order["sell_uid"]."-".$view_order["sell_user_name"];
        $orderRecordResult =$this->create_order_record($view_order["id"],$view_order["sell_sn"],$record,$mark);
        if (!$orderRecordResult){
            return "订单记录修改失败";
        }
        //5 - 设置账户未激活账户
        $sn = $view_order["sell_sn"];
        $maker = "订单(".$sn.")卖家申诉成功- 【未激活】";
        $user=Db::table("tb_user")->where("id",$view_order["buy_id"])->find();
        return $this->userHelper->userActivity($user,$maker,false);
    }


    /**
     * 订单申诉失败（卖家申诉）
     * @param $order
     * @param $appeal
     */
    public function orderAppealSellFail($view_order,$appeal) {
        //卖家申诉失败；则走订单确认流程

        $appealData=[];
        // 1 改变申诉表 申诉状态
        //0 申述中 1 卖家申述成功 2 卖家申述失败
        $appealData["appeal_result"]=2;
        $appealData["finish_time"]=date('Y-m-d H:i:s');
        $appealResult =  Db::table("tb_mt_appeal")->where("id",$appeal["id"])->update($appealData);
        if (!$appealResult){
            return "申诉表改变状态失败";
        }
        // 1 走订单确认流程
        $mark="卖家申诉失败,走确认订单流程";
        $orderResult =  $this->orderConfirm($view_order,$mark);
        return $orderResult;
    }


    /**
     * 订单确认
     * @param $order
     */
    public function orderConfirm($view_order,$mark) {
        $data =[];
        $data["order_status"]=3;
        $data["confirm_time"]=date('Y-m-d H:i:s');
        $data["finish_time"]=date('Y-m-d H:i:s');
        $resOrder =  Db::table("tb_mt_order")->where("id",$view_order["id"])->update($data);
        if (!$resOrder){
            return "订单表修改失败";
        }
        $bRecord =[];
        $bRecord["money"]=$view_order["sell_price"];
        $bRecord["bank"]=$view_order["pay_bank_id"];
        $bRecord["time"]=date('Y-m-d H:i:s');
        $bRecord["type"]=1;
        $bRecord["mark"]=$mark;
        $resbank =  Db::table("tb_mt_bank_money")->insert($bRecord);
        if (!$resbank){
            return "统计表入库失败";
        }
        $resbank1 =  Db::table("tb_mt_bank")->where("id",$view_order["pay_bank_id"])->setInc("t_money",$view_order["sell_price"]);

        if (!$resbank1){
            return "统计累计增收款失败";
        }
        $resbank2 =  Db::table("tb_mt_bank")->where("id",$view_order["pay_bank_id"])->setInc("d_money",$view_order["sell_price"]);
        if (!$resbank2){
            return "统计今日增收款失败";
        }
        //卖家是否 是系统
        $buyUserIsSystem = $view_order["buy_id"]==0;

        //订单修改记录
        $record= $buyUserIsSystem?"系统收单:".$mark:$mark;
        $mark = $view_order["sell_uid"]."-".$view_order["sell_user_name"];
        $orderRecordResult = $this->create_order_record($view_order["id"],$view_order["sell_sn"],$record,$mark);
        if (!$orderRecordResult){
            return "订单记录入库失败";
        }


        //生成一个新的卖单
        //如果是不是系统收单 创建一个新订单
       if (!$buyUserIsSystem){
           return $this->sell->createUserSell($view_order);
       }
       return 1;
    }

    /**
     * 订单取消
     * @param $order
     */
    public function orderCancle($view_order,$mark) {
        $data =[];
        $data["order_status"]=4;
        $data["cancle_time"]=date('Y-m-d H:i:s');
        $data["finish_time"]=date('Y-m-d H:i:s');
        $resOrder =  Db::table("tb_mt_order")->where("id",$view_order["id"])->update($data);
        if (!$resOrder){
            return "订单修改失败";
        }

        //1 收益中 2 匹配中 3 用户取消再次待卖 4 申述成功再次待卖 5销毁 6判定代卖 7 完成
        $updateSell = [];
        $updateSell["status"]=3;
        $resSell =  Db::table("tb_mt_sell")->where("id",$view_order["sell_id"])->update($updateSell);
        if (!$resSell){
            return "出售表更新失败";
        }

        //订单修改记录
        $record= $mark;
        $mark = "卖家".$view_order["sell_uid"]."-".$view_order["sell_user_name"];

        $orderRecordResult =$this->create_order_record($view_order["id"],$view_order["sell_sn"],$record,$mark);
        if (!$orderRecordResult){
            return "订单记录修改失败";
        }
        //禁用账户
        $sn = $view_order["sell_sn"];
        $maker = "订单(".$sn.")被取消- 【未激活】";
        $user=Db::table("tb_user")->where("id",$view_order["buy_id"])->find();
        return $this->userHelper->userActivity($user,$maker,false);
    }

    /**
     * 订单支付了
     * @param $order
     * @param $payData 用户提交数据
     * @param $bank 用户支付银行卡
     */
    public function orderPay($view_order,$payData,$bank) {
        $data =[];
        $data["order_status"]=2;
        $data["pay_time"]=date('Y-m-d H:i:s');
        $data["pay_img"]=$payData["pay_img"];
        $data["pay_bank_id"]=$bank["id"];
        $data["pay_bank_json"]=json_encode($bank);
        $resOrder =  Db::table("tb_mt_order")->where("id",$view_order["id"])->update($data);
        if (!$resOrder){
            return "订单操作失败";
        }
        //订单修改记录
        $record= "用户支付了订单";
        $mark =$bank["uid"]==0?"系统支付":"支付人:".$view_order["buy_id"]."-".$view_order["buy_name"] ;
        $orderRecordResult = $this->create_order_record($view_order["id"],$view_order["sell_sn"],$record,$mark);
        if (!$orderRecordResult){
            return "订单记录入库失败";
        }
        Redis::hset("order_status_confirm",$view_order["sell_uid"],1);
        return 1;
    }

    /**
     * 订单判定
     * @param $view_order
     */
    public function orderPanding($view_order){
        //1----- 买家 买了此订单 生成了出售订单处理
        $sell_next_id =$view_order["sell_next_id"];
        $buy_new_sell = Db::table("tb_mt_sell")->where('id', $sell_next_id)->find();
        if (!$buy_new_sell){
            return "此订单没有接盘人生成的订单；不能判定";
        }
        // status 1 收益中 2 匹配中 3 用户取消再次待卖 4 申述成功再次待卖 5销毁 6判定代卖 7 完成 8 判定终止
        // 新订单在 没有在匹配中 或者 已完成  判定终止 可以判定
        if ($buy_new_sell["status"]==2){
            return "接盘订单在匹配中；不能判定";
        }
        if ($buy_new_sell["status"]==5){
            return "接盘订单在已销毁；不能判定";
        }
        if ($buy_new_sell["status"]==7){
            return "接盘订单已完成；不能判定";
        }
        if ($buy_new_sell["status"]==8){
            return "接盘订单已被判定过；不能判定";
        }
        if ($buy_new_sell["status"]==6){
            return "接盘订单已被判待卖；不能判定";
        }
        //改变接盘人订单 为 判定终止
        $id = $view_order["sell_id"];
        // 2 ---修改出售表为判定 1 收益中 2 匹配中 3 用户取消再次待卖 4 申述成功再次待卖 5销毁 6判定代卖 7 完成 8 判定终止
        $updateData=[];
        $updateData["status"] =8;
        $res = Db::table("tb_mt_sell")->where('id', $sell_next_id)->update($updateData);
        if (!$res){
            return "将接盘人订单设为判定终止报错";
        }
        //3----接盘人 订单 如果有已完成订单 则不能判定 所以 不需要修改订单表
        // 接盘人 出售表 状态变更 需要做记录
        $record= "订单判定接盘订单终止";
        $mark = "系统人员判定:接盘sn:".$view_order["sell_next_sn"];
        $resRecord = $this->create_order_record($id,$view_order["sell_sn"],$record,$mark);
        if (!$resRecord){
            return "新增接盘人订单修改记录失败";
        }

        $id = $view_order["sell_id"];
        // 4 ---修改出售表为判定 1 收益中 2 匹配中 3 用户取消再次待卖 4 申述成功再次待卖 5销毁 6判定代卖 7 完成 8判定终止
        $updateData=[];
        $updateData["status"] =6;
        $res = Db::table("tb_mt_sell")->where('id', $id)->update($updateData);
        if (!$res){
            return "判定订单 修改出售人订单为 判定代卖状态失败";
        }
        // 3 ---- 修改订单状态
        //1待支付 2 待确认 3 已完成 4 取消 5申诉中 6申诉成功，7判定
        $data =[];
        $data["order_status"]=7;
        $data["cancle_time"]=date('Y-m-d H:i:s');
        $resOrder =  Db::table("tb_mt_order")->where("id",$view_order["id"])->update($data);
        if (!$resOrder){
            return "订单修改失败";
        }
        $record= "订单判定成功，订单将重新出售";
        $mark = "系统人员判定:接盘sn:".$view_order["sell_next_sn"];
        $resRecord = $this->create_order_record($id,$view_order["sell_sn"],$record,$mark);
        if ($resRecord){
            return 1;
        }
        return "记录订单出错";
    }


    /**
     * 创建订单修改记录
     * @param $order
     */
    private function create_order_record($oid,$sn,$record,$mark="") {
        $data =[];
        $data["oid"]=$oid;
        $data["sn"]=$sn;
        $data["record"]=$record;
        $data["mark"]=$mark;
        $data["time"]=date('Y-m-d H:i:s');
         return  Db::table("tb_mt_order_record")->insert($data);

    }




}